package cn.jjxx.modules.screen.controller;

import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson; 
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.PropertiesUtil;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.core.utils.upload.FileUploadUtils;
import cn.jjxx.core.utils.upload.exception.FileNameLengthLimitExceededException;
import cn.jjxx.core.utils.upload.exception.InvalidExtensionException;

import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeFilter; 
import com.beust.jcommander.internal.Lists;

import org.apache.commons.fileupload.FileUploadBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.jjxx.core.common.controller.BaseBeanController; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import cn.jjxx.modules.screen.entity.BigScreenInfo;
import cn.jjxx.modules.screen.entity.ScreenInfo;
import cn.jjxx.modules.screen.service.IBigScreenInfoService; 
import cn.jjxx.modules.screen.vo.SuccessResponse;
import cn.jjxx.modules.sys.entity.Attachment;
import cn.jjxx.modules.sys.service.IAttachmentService;
import cn.jjxx.modules.map.service.ICommonMapService;
/**   
 * @Title: big_screen_info
 * @Description: big_screen_info
 * @author yx
 * @date 2022-05-07 09:39:56
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/api/screen") 
public class ScreenApiController extends BaseBeanController<BigScreenInfo> {

	@Autowired
	protected IBigScreenInfoService bigScreenInfoService;
	@Autowired
	protected ICommonMapService commonMapService;


	@Autowired
	private IAttachmentService attachmentService;


	/**
	 * @Description: 根据获取big_screen_info的实体数据 .<br>
	 * @param id 主键Id.<br>
	 * @author yx .<br>
	 * @date 2022-05-07 09:39:56.<br>
	 */
	public BigScreenInfo get(String id) {
		if (!ObjectUtils.isNullOrEmpty(id)) {
			return bigScreenInfoService.selectById(id);
		} else {
			return newModel();
		}
	} 

	/**
	 * 查询列表数据
	 *@Title ScreenApiController.java
	 *@description TODO
	 *@time 2022年5月7日 上午11:43:55
	 *@author YAOXIONG
	 *@version 1.0
	 *
	 */
	@RequestMapping(value = "list")
	@ResponseBody   
	private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		EntityWrapper<BigScreenInfo> entityWrapper = new EntityWrapper<BigScreenInfo>(entityClass);
		propertyPreFilterable.addQueryProperty("id");
		String enable = request.getParameter("enable");
		if (!StringUtils.isEmpty(enable)) {//状态
			entityWrapper.eq("enable", enable)	;
		}
		String keyword = request.getParameter("keyword");
		if (!StringUtils.isEmpty(keyword)) {//关键值
			entityWrapper.like("name", keyword)	;
			entityWrapper.like("remark", keyword)	;
		}
		String typeId = request.getParameter("typeId");
		String pages = request.getParameter("page");
		if (!StringUtils.isEmpty(typeId)) {//类型
			entityWrapper.eq("typeId", typeId)	;
		}
		entityWrapper.eq("delflag", 0)	;
		entityWrapper.orderBy("createTime", false);
		// 预处理
		QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);

		PageJson<BigScreenInfo> pagejson = new PageJson<BigScreenInfo>(bigScreenInfoService.list(pages,queryable,entityWrapper));
		List<ScreenInfo> retList = Lists.newArrayList();
		for (BigScreenInfo bigScreenInfo : pagejson.getResults()) {
			ScreenInfo screen = new ScreenInfo();
			screen.setId(bigScreenInfo.getId());
			screen.setCreateTime(bigScreenInfo.getCreateTime());
			screen.setDelflag(bigScreenInfo.getDelflag());
			screen.setEnable(bigScreenInfo.getEnable());
			screen.setHeight(bigScreenInfo.getHeight());
			screen.setWidth(bigScreenInfo.getWidth());
			screen.setName(bigScreenInfo.getName());
			screen.setRemark(bigScreenInfo.getRemark());
			screen.setTypeId(bigScreenInfo.getTypeId());
			retList.add(screen);
		}
		//拼接数据格式
		PageJson<ScreenInfo> pagejson1 = new PageJson<ScreenInfo>(retList);
		JSONObject json = new JSONObject();
		json.put("page", pagejson.getPage()+1);
		json.put("pages", pagejson.getTotalPages());
		json.put("size",pagejson.getRows());
		json.put("total", pagejson.getTotal());
		json.put("list", pagejson1.getResults());
		String content = JSON.toJSONString(json, filter);
		StringUtils.printJson(response, content);
	}

	/**
	 * 根据ID查询数据
	 *@Title ScreenApiController.java
	 *@description TODO
	 *@time 2022年5月7日 下午12:24:02
	 *@author YAOXIONG
	 *@version 1.0
	 *
	 */
	@RequestMapping(value = "{id}")
	@ResponseBody   
	private void screenInfo(HttpServletRequest request,
			HttpServletResponse response,@PathVariable("id") String screenId) throws IOException {

		String content = JSON.toJSONString(get(screenId));
		StringUtils.printJson(response, content);
	}

	/**
	 * 保存数据
	 *@Title ScreenApiController.java
	 *@description TODO
	 *@time 2022年5月7日 下午12:38:41
	 *@author YAOXIONG
	 *@version 1.0
	 *
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public SuccessResponse doSave(@RequestBody @Validated BigScreenInfo bigScreenInfo, HttpServletRequest request, HttpServletResponse response,
			BindingResult result) {
		SuccessResponse resp = SuccessResponse.success();
		if (hasError(bigScreenInfo, result)) {
			// 错误提示
			String errorMsg = errorMsg(result);
			if (!StringUtils.isEmpty(errorMsg)) {
				resp = SuccessResponse.success(errorMsg);
			} else {
				resp = SuccessResponse.success("保存失败");
			}
			return resp;
		}
		try {
			bigScreenInfoService.insert(bigScreenInfo);
		} catch (Exception e) {
			e.printStackTrace();
			resp = SuccessResponse.success("保存失败!<br />原因:" + e.getMessage());
		}
		return resp;
	}

	/**
	 * 修改状态
	 *@Title ScreenApiController.java
	 *@description TODO
	 *@time 2022年5月7日 下午12:38:48
	 *@author YAOXIONG
	 *@version 1.0
	 *
	 */
	@RequestMapping(value = "/status", method = RequestMethod.POST)
	@ResponseBody
	public SuccessResponse status(@RequestParam("id") String screenId) { 
		SuccessResponse resp = SuccessResponse.success();
		try {
			BigScreenInfo bigScreenInfo = get(screenId);
			if (bigScreenInfo.getEnable() == 0) {
				bigScreenInfo.setEnable(1);
			}else {
				bigScreenInfo.setEnable(0);
			}
			bigScreenInfoService.updateById(bigScreenInfo);
		} catch (Exception e) {
			e.printStackTrace();
			resp = SuccessResponse.success("保存失败!<br />原因:" + e.getMessage());
		}
		return resp;
	}
	/**
	 * 复制模板
	 *@Title ScreenApiController.java
	 *@description TODO
	 *@time 2022年5月7日 下午12:40:29
	 *@author YAOXIONG
	 *@version 1.0
	 *
	 */
	@RequestMapping(value = "/copy", method = RequestMethod.POST)
	@ResponseBody
	public SuccessResponse copyScreenInfo(@RequestParam("id") String screenId) {
		this.bigScreenInfoService.copyScreenInfo(screenId);
		return SuccessResponse.success();
	}
	/**
	 * 删除
	 *@Title ScreenApiController.java
	 *@description TODO
	 *@time 2022年5月7日 下午1:07:03
	 *@author YAOXIONG
	 *@version 1.0
	 *
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public SuccessResponse delete(@RequestParam("id") String screenId) {
		SuccessResponse resp = SuccessResponse.success();
		try {
			BigScreenInfo bigScreenInfo = get(screenId);
			bigScreenInfo.setDelflag(1);
			bigScreenInfoService.updateById(bigScreenInfo);
		} catch (Exception e) {
			e.printStackTrace();
			resp = SuccessResponse.success("保存失败!<br />原因:" + e.getMessage());
		}
		return resp;
	}


	/**
	 * @title: ajaxUpload
	 * @description: 文件上传
	 * @param request
	 * @param response
	 * @param files
	 * @return
	 * @return: AjaxUploadResponse
	 */
	@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
	@ResponseBody
	public void upload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file) { 
		PropertiesUtil propertiesUtil = new PropertiesUtil("upload.properties");
		String baseDir = propertiesUtil.getString("upload.base.dir"); 
		Attachment attachment = new Attachment();
		String url = null;
		try {  
			try {
				attachment = attachmentService.specifyUpload(request, file,baseDir+"/screen/upload");
				url = attachment.getFilepath(); 
			} catch (Exception e) {
				// TODO Auto-generated catch block
				url = (MessageUtils.getMessage("upload.server.error"));
			}  
		} catch (Exception e) {
			url = (MessageUtils.getMessage("upload.server.error"));
		}  
		JSONObject json = new JSONObject();
		json.put("message", "/"+url); 
		StringUtils.printJson(response, json);
	}
}
